package com.yunquan.ohana.ui.calendar.event

import android.os.Bundle
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.doOnLayout
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityCalendarEventBinding
import com.yunquan.ohana.entity.FramesDataManager
import com.yunquan.ohana.ui.calendar.event.adapter.EventPagerAdapter
import com.yunquan.ohana.ui.calendar.event.dialog.EventSyncDialog
import com.yunquan.ohana.ui.calendar.event.month.EventMonthFragment
import com.yunquan.ohana.ui.calendar.event.week.EventWeekFragment
import com.yunquan.ohana.ui.scan.ScanActivity
import java.time.LocalDateTime
import java.util.Locale

class EventActivity : BaseActivity<ActivityCalendarEventBinding, EventViewModel>() {

    lateinit var mWeekAdapter: EventPagerAdapter
    lateinit var mMonthAdapter: EventPagerAdapter

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_calendar_event
    }

    override fun initVariableId(): Int {
        return BR.eventViewModel
    }

    override fun initParam() {
        super.initParam()
        Locale.setDefault(Locale("en"))
        // 设置背景颜色
        window.statusBarColor = ContextCompat.getColor(this, R.color.white)
        // 设置文字颜色（true = 黑色文字，false = 白色文字）
        val controller = WindowInsetsControllerCompat(window, window.decorView)
        controller.isAppearanceLightStatusBars = true
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        viewModel!!.mDeviceId = intent.extras?.getString("deviceId")
        viewModel!!.userType = intent.extras?.getBoolean("userType")
        mWeekAdapter = EventPagerAdapter(
            this,
            true,
            viewModel!!.mDeviceId!!,
            viewModel!!.userType ?: false,
        )
        mMonthAdapter = EventPagerAdapter(
            this,
            false,
            viewModel!!.mDeviceId!!,
            viewModel!!.userType ?: false,
        )

        binding!!.vpWeek.adapter = mWeekAdapter
        binding!!.vpWeek.offscreenPageLimit = 1
        binding!!.vpWeek.setCurrentItem(mWeekAdapter.basePosition, false)
        // 优化 ViewPager2 底层 RecyclerView，关闭预取与动画，减少滑动卡顿
        (binding!!.vpWeek.getChildAt(0) as? androidx.recyclerview.widget.RecyclerView)?.let { rv ->
            rv.itemAnimator = null
            rv.overScrollMode = android.view.View.OVER_SCROLL_NEVER
            rv.isNestedScrollingEnabled = false
            (rv.layoutManager as? androidx.recyclerview.widget.LinearLayoutManager)?.isItemPrefetchEnabled = false
            rv.setItemViewCacheSize(2)
        }
        viewModel!!.mZoneIndex = mWeekAdapter.basePosition
        viewModel!!.mWeekCurrentIndex = mWeekAdapter.basePosition

        binding!!.vpMonth.adapter = mMonthAdapter
        binding!!.vpMonth.offscreenPageLimit = 1
        binding!!.vpMonth.setCurrentItem(mMonthAdapter.basePosition, false)
        (binding!!.vpMonth.getChildAt(0) as? androidx.recyclerview.widget.RecyclerView)?.let { rv ->
            rv.itemAnimator = null
            rv.overScrollMode = android.view.View.OVER_SCROLL_NEVER
            rv.isNestedScrollingEnabled = false
            (rv.layoutManager as? androidx.recyclerview.widget.LinearLayoutManager)?.isItemPrefetchEnabled = false
            rv.setItemViewCacheSize(2)
        }
        viewModel!!.mZoneIndex = mMonthAdapter.basePosition
        viewModel!!.mMonthCurrentIndex = mMonthAdapter.basePosition

        // 注册翻页回调：仅在滚动停止（SCROLL_STATE_IDLE）后加载当前页数据，实现懒加载 & 每次进入页都刷新
        binding!!.vpWeek.registerOnPageChangeCallback(object : androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback() {
            private var selected = viewModel!!.mWeekCurrentIndex
            override fun onPageSelected(position: Int) {
                selected = position
            }

            override fun onPageScrollStateChanged(state: Int) {
                if (state == androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE) {
                    (mWeekAdapter.getFragment(selected) as? EventWeekFragment)?.viewModel?.getEventData()
                }
            }
        })

        binding!!.vpMonth.registerOnPageChangeCallback(object : androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback() {
            private var selected = viewModel!!.mMonthCurrentIndex
            override fun onPageSelected(position: Int) {
                selected = position
            }

            override fun onPageScrollStateChanged(state: Int) {
                if (state == androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE) {
                    (mMonthAdapter.getFragment(selected) as? EventMonthFragment)?.viewModel?.getEventData()
                }
            }
        })
        binding!!.vpWeek.doOnLayout {
            // 首次进入页面，主动加载当前可见页的数据
            if (viewModel!!.mIsWeek.get() == true) {
                (mWeekAdapter.getFragment(viewModel!!.mWeekCurrentIndex) as? EventWeekFragment)?.viewModel?.getEventData()
            } else {
                (mMonthAdapter.getFragment(viewModel!!.mMonthCurrentIndex) as? EventMonthFragment)?.viewModel?.getEventData()
            }
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        // 监听来自 ViewModel 的 UI 事件
        viewModel!!.ui.observe(this) {
            when (it) {
                // 跳转到选中日期所在的周视图页
                1 -> {
                    // 切换单选为周模式（会触发 onGroupChange，更新 mIsWeek 与标题）
                    binding!!.rgChoose.check(R.id.rb_week)
                    // 跳转到对应的周页
                    binding!!.vpWeek.setCurrentItem(viewModel!!.mWeekCurrentIndex, false)
                    binding!!.vpWeek.post {
                        viewModel!!.isGoWeek = false
                        (mWeekAdapter.getFragment(viewModel!!.mWeekCurrentIndex) as? EventWeekFragment)?.viewModel?.getEventData()
                    }
                }

                2 -> {
                    if (viewModel!!.mIsWeek.get() == true) {
                        (mWeekAdapter.getFragment(viewModel!!.mWeekCurrentIndex) as? EventWeekFragment)?.viewModel?.getEventData()
                    } else {
                        (mMonthAdapter.getFragment(viewModel!!.mMonthCurrentIndex) as? EventMonthFragment)?.viewModel?.getEventData()
                    }
                }
            }
        }
        binding!!.tvCurrDay.setOnClickListener {
            if (viewModel!!.mIsWeek.get() == true) {
                binding!!.vpWeek.setCurrentItem(viewModel!!.mZoneIndex, true)
                binding!!.vpWeek.post {
                    viewModel!!.mLocaleDateTime = LocalDateTime.now()
                    viewModel!!.setCurrentDay()
                }
            } else {
                binding!!.vpMonth.setCurrentItem(viewModel!!.mZoneIndex, true)
                binding!!.vpMonth.post {
                    viewModel!!.mLocaleDateTime = LocalDateTime.now()
                    viewModel!!.setCurrentDay()
                }
            }
        }
        binding!!.tvSync.setOnClickListener {
            val deviceList = FramesDataManager.instance.getData().filter {
                it.id != viewModel!!.mDeviceId
            }.toMutableList()


            val dialog = EventSyncDialog(
                context = this,
                mSyncDialogResult,
                devices = deviceList,
            )
            dialog.setOnBindDeviceListener { code ->
                viewModel!!.bindFrames(code, getCurrentEventList())
            }
            dialog.setOnSelectDeviceListener { devices ->
                viewModel!!.syncToDevice(devices, getCurrentEventList())
            }
            dialog.show()
        }
    }

    private fun getCurrentEventList(): List<String> {
        val eventList = mutableListOf<String>()
        if (viewModel!!.mIsWeek.get() == true) {
            (mWeekAdapter.getFragment(viewModel!!.mWeekCurrentIndex) as? EventWeekFragment)?.viewModel?.items?.forEach { item ->
                item.items.forEach {
                    eventList.add(it.data!!.id!!)
                }
            }
        } else {
            (mMonthAdapter.getFragment(viewModel!!.mMonthCurrentIndex) as? EventMonthFragment)?.viewModel?.items?.forEach { item ->
                item.items.forEach {
                    eventList.add(it.data!!.id!!)
                }
            }
        }
        return eventList.distinct()
    }

    // 这里处理返回结果
    private val mSyncDialogResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == ScanActivity.RESULT_CODE) {
            // 扫描二维码返回
            val bundle = result.data?.extras
            val text = bundle?.getString("text")
            text?.let {
                viewModel!!.bindFrames(it, getCurrentEventList())
            }
        }
    }

    override fun onActivityResult(result: ActivityResult) {
        super.onActivityResult(result)
        if (result.resultCode == 1002) {
            (mWeekAdapter.getFragment(viewModel!!.mWeekCurrentIndex) as? EventWeekFragment)?.viewModel?.getEventData()
            (mMonthAdapter.getFragment(viewModel!!.mMonthCurrentIndex) as? EventMonthFragment)?.viewModel?.getEventData()
        } else if (result.resultCode == 1003) {
            (mWeekAdapter.getFragment(viewModel!!.mWeekCurrentIndex) as? EventWeekFragment)?.viewModel?.getEventData()
            (mMonthAdapter.getFragment(viewModel!!.mMonthCurrentIndex) as? EventMonthFragment)?.viewModel?.getEventData()
        }
    }
}